//
//  YLIntegralMallController.m
//  YLFinanceService
//
//  Created by she1323 on 2017/9/5.
//  Copyright © 2017年 she1323. All rights reserved.
//  积分商城

#import "YLIntegralMallController.h"
#import "YLGlobeHeader.h"
#import "YLMallSlideImageHeaderView.h"
#import "YLMallSlideImageHeader.h"
#import "YLMallTitleCollectionViewCell.h"
#import "YLIntegralMallViewModel.h"
#import "YLMallItemCollectionViewCell.h"
#import "YLMallIconHeader.h"
#import "YLMallGoodsCollectionViewCell.h"
#import "ULBCollectionViewFlowLayout.h"
#import "YLGoodsDetailViewController.h"
#import "YLExchangeRecordController.h"
#import "YLMallGoodModel.h"
#import "YLMallTitleModel.h"
#import "YLMallItemModel.h"
#import <MJRefresh.h>
#import "YLIntegralController.h"
#import "YLMineViewModel.h"
#import "YLMyInfoModel.h"
@interface YLIntegralMallController ()<UICollectionViewDelegateFlowLayout, ULBCollectionViewDelegateFlowLayout>
@property (nonatomic, strong) YLIntegralMallViewModel *viewModel;

@property (nonatomic, strong) YLMineViewModel *mineViewModel;

@property (nonatomic, assign) BOOL loadMyInfo;

@property (nonatomic, assign) NSInteger index;
@end

@implementation YLIntegralMallController


- (YLIntegralMallViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[YLIntegralMallViewModel alloc] init];
    }
    return _viewModel;
}

- (YLMineViewModel *)mineViewModel
{
    if (!_mineViewModel) {
        _mineViewModel = [[YLMineViewModel alloc] init];
    }
    return _mineViewModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"积分商城";
    
    _loadMyInfo = NO;
    
    self.view.backgroundColor = YLColor(248, 249, 252);
    
    self.collectionView.backgroundColor = YLColor(248, 249, 252);
    
    [self.collectionView registerClass:[YLMallSlideImageHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[YLMallSlideImageHeader headID]];
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YLMallTitleCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:[YLMallTitleCollectionViewCell cellID]];
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YLMallItemCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:[YLMallItemCollectionViewCell cellID]];
    
    [self.collectionView registerClass:[YLMallIconHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[YLMallIconHeader headerID]];
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YLMallGoodsCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:[YLMallGoodsCollectionViewCell cellID]];
    
    
    __weak typeof(self) weakSelf = self;
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.index = 1;
        [weakSelf loadData];
    }];
    
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.index ++;
        [weakSelf loadData];
    }];
    
    self.collectionView.mj_footer.hidden = YES;
    
    [self.collectionView.mj_header beginRefreshing];
    
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // == yes 说明 viewModel 有数据了 可以改了
    
    if (_loadMyInfo) {
        __weak typeof(self) weakSelf = self;
        [[self.mineViewModel.myInfoCommand execute:nil] subscribeNext:^(id  _Nullable x) {
            
            NSArray *mallTitles = weakSelf.viewModel.groups.firstObject;
            
   
            YLMallTitleModel *model = mallTitles.firstObject;
            model.content = [NSString stringWithFormat:@"%zd", weakSelf.mineViewModel.myInfoModel.pointQuota];
            weakSelf.viewModel.totalPoint = model.content;
            [weakSelf.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]];
        }];
    }
 
}

- (void)loadData
{
    __weak typeof(self) weakSelf = self;
    [[self.viewModel.productListCommand execute:@(_index)] subscribeNext:^(id  _Nullable x) {
        [weakSelf.collectionView reloadData];
        weakSelf.collectionView.mj_footer.hidden = NO;
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        
        weakSelf.loadMyInfo = YES;
        
    }];
    
    [self.viewModel.wh_noMoreDataSubject subscribeNext:^(id  _Nullable x) {
        [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
    }];
    
    [self.viewModel.wh_loadDataErrorSubject subscribeNext:^(id  _Nullable x) {
        weakSelf.collectionView.mj_footer.hidden = NO;
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
    }];
}

- (instancetype)init
{
    ULBCollectionViewFlowLayout *layout = [[ULBCollectionViewFlowLayout alloc] init];
    return [self initWithCollectionViewLayout:layout];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.viewModel.groups.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *items = self.viewModel.groups[section];
    return items.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *cell = nil;
    NSArray *items = self.viewModel.groups[indexPath.section];
    id model = items[indexPath.item];

    if ([model isKindOfClass:[YLMallGoodModel class]]) {
        NSArray *array = self.viewModel.groups.lastObject;
        YLMallGoodsCollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:[YLMallGoodsCollectionViewCell cellID] forIndexPath:indexPath];
        cell.model = array[indexPath.row];
        return cell;
    } else if ([model isKindOfClass:[YLMallTitleModel class]]) {
        YLMallTitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[YLMallTitleCollectionViewCell cellID] forIndexPath:indexPath];
        cell.model = (YLMallTitleModel *)model;
        return cell;
    } else if([model isKindOfClass:[YLMallItemModel class]]) {
        YLMallItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[YLMallItemCollectionViewCell cellID] forIndexPath:indexPath];
        cell.model = (YLMallItemModel *)model;
        return cell;
    }
    
    if (cell == nil) {
        cell = [[UICollectionViewCell alloc] init];
    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *resuableView = nil;
    
    if (kind == UICollectionElementKindSectionHeader) {
        if (indexPath.section == 0) {
            YLMallSlideImageHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:[YLMallSlideImageHeader headID] forIndexPath:indexPath];
            resuableView = headerView;
        } else if (indexPath.section == 2) {
            YLMallIconHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[YLMallIconHeader headerID] forIndexPath:indexPath];
            resuableView = headerView;
        }
    }
    
    if (resuableView == nil) {
        resuableView = [[UICollectionReusableView alloc] init];
    }
    
    return resuableView;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    if (section == 1) {
        return YLScreenW - YLWidth(160) - YLWidth(60);
    }
    return 0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(YLScreenW / 2.0, YLScreenW / 2.0 * 120 / 370.0);
    } else if (indexPath.section == 1) {
        return CGSizeMake(YLWidth(80), 100);
    } else {
        return CGSizeMake(YLScreenW / 2 - 1, 215);
    }
    return CGSizeZero;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        return UIEdgeInsetsZero;
    } else if (section == 1) {
        return UIEdgeInsetsMake(5, YLWidth(30), 5, YLWidth(30));
    } else if (section == 2) {
        return UIEdgeInsetsMake(2, 0, 0, 0);
    }
    return UIEdgeInsetsZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(YLScreenW, YLScreenW * 0.49);
    } else if (section == 2) {
        return CGSizeMake(YLScreenW, YLScreenW * 290 / 1030.0);
    }
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeZero;
}

- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout colorForSectionAtIndex:(NSInteger)section
{
    if (section == 2) {
        return [UIColor clearColor];
    }
    return [UIColor clearColor];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
       NSArray *items = self.viewModel.groups[indexPath.section];
        YLMallTitleModel *model = items[indexPath.item];
        if (model.clickBlock) {
             NSString *className =  model.clickBlock();
            
            if ([className isEqualToString:@"YLIntegralController"]) {
                YLIntegralController *con = [[YLIntegralController alloc] init];
                con.totalPoint = self.viewModel.totalPoint;
                [self.navigationController pushViewController:con animated:YES];
                return;
            }
            
            [self.navigationController pushViewController:[[NSClassFromString(className) alloc] init] animated:YES];
        }
    }
    
    if (indexPath.section == 1) {
        NSArray *items = self.viewModel.groups[indexPath.section];
        YLMallItemModel *model = items[indexPath.item];
        if (model.clickBlock) {
            NSString *className =  model.clickBlock();
            if (className.length > 0) {
                [self.navigationController pushViewController:[[NSClassFromString(className) alloc] init] animated:YES];
            }
        }
    }
    
    
    if (indexPath.section == 2) {
        NSArray *items = self.viewModel.groups[indexPath.section];
        YLMallGoodModel *model = items[indexPath.item];
        YLGoodsDetailViewController *detail = [[YLGoodsDetailViewController alloc] init];
        detail.pointProductId = model.pointProductId;
        detail.pointQuota = [self.viewModel.totalPoint integerValue];
//        detail.model = model;
        [self.navigationController pushViewController:detail animated:YES];
    }
}

@end
